#include "DebugLog.h"
#include "DXWindow.h"
#include "DX.h"
#include "WindowController.h"
#include "Window.h"
#include "Application.h"
#include "NCenter.h"
#include "Animation.h"

Application* Application::__ = 0;

Application* Application::_( )
{
	return ( __ ) ? __ : __ = new Application( );
}

Application::Application( ) : nCenter ( new NCenter() ), _windowController( 0 )
{
	
}

Application::~Application( )
{
	delete Animation::_();
	delete _windowController;
	delete nCenter;
	delete DX::_();

#ifdef _DEBUG
	//delete DebugLog::_();
#endif
}

void Application::setWindowController( WindowController* winController )
{
	if ( windowController() != winController )
	{
		delete _windowController;
		_windowController = winController;
	}
}

WindowController* Application::windowController()
{
	if ( !_windowController ) 
	{
		_windowController = new WindowController();
	}
	return _windowController;
}

void Application::Run( )
{
	MSG msg = { 0 };

	// if contentView in window not set ( custom view controller ) than create default
	windowController()->viewController();

	while( 1 )
	{
		while ( PeekMessage( &msg, 0, 0, 0, PM_REMOVE ) )
		{
			if ( msg.message == WM_QUIT ) return;

			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		
		windowController()->window()->update( );

		Sleep( 15 );

		( *Animation::_() )();
		( *nCenter )();

#if defined(FULLSCREEN)
		testCooperateLevel();
#endif

	}
}

void Application::testCooperateLevel()
{
	switch ( DX::_()->device->TestCooperativeLevel() )
	{
		case D3DERR_DEVICELOST:
		{
			
			break;
		}
		
		case D3DERR_DEVICENOTRESET:
		{
			if ( D3D_OK == DX::_()->device->Reset( &DX::_()->d3dpp ) ){
				DX::_()->init( DX::_()->_hWnd );
			}
			break;
		}

		case D3D_OK:
		{
				
			break;
		}
	}
}